<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="UTF-8">
    <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
    <meta name="robots" content="noindex" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="./favicon.png" />
    <title>Account Reset | Zoraxy</title>
    <link rel="stylesheet" href="script/semantic/semantic.min.css">
    <link href="script/aos.css" rel="stylesheet">
    <script src="script/aos.js"></script>
    <script type="application/javascript" src="script/jquery-3.6.0.min.js"></script>
    <script type="application/javascript" src="script/semantic/semantic.min.js"></script>
    <style>
        body {
            background: rgb(38,60,71);
            background: linear-gradient(215deg, rgba(38,60,71,1) 13%, rgba(2,3,42,1) 84%); 
        }

        .background{
            position: fixed;
            top: 0;
            right: 0;
            height: 100%;
            width: 100%;
            opacity: 0.8;
            z-index: -99;
            background-image: url("img/public/bg2.jpg");
            background-size: auto 100%;
            background-position: right top;
            background-repeat: no-repeat;
            overflow-x: hidden;
        }

        form {
            margin:auto;
        }

        #errmsg{
            color: #9f3a38;
            margin-top: 1em;
            margin-bottom: 0.4em;
            text-align: left;
        }

        .backBtn{
            position: absolute;
            top: 0em;
            left: 2em;
            transition: opacity 0.3s linear;
        }

        .backBtn:hover{
            opacity: 0.8;
        }

        #loginForm {
                border-radius: 1em;
                width: 25em;
                height: 550px;
                position: absolute; /*Can also be `fixed`*/
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
                /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
                max-width: 100%;
                max-height: 100%;
                overflow: auto;
                background-color: white;
        }

        .wavebase {
            position:fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height:5vh;
            text-align:center;
            padding-top: 1em;
            background-color: white;
        }

        /* 
            Waves CSS 
        */

        #wavesWrapper{
            position: fixed;
            bottom: 5vh;
            width: 100%;
            left: 0;
        }
        
        .waves {
            position:relative;
            width: 100%;
            height:15vh;
            margin-bottom:-7px; /*Fix for safari gap*/
            min-height:100px;
            max-height:150px;
        }

        
        .parallax > use {
            animation: move-forever 25s cubic-bezier(.55,.5,.45,.5)     infinite;
        }
        .parallax > use:nth-child(1) {
            animation-delay: -8s;
            animation-duration: 28s;
        }
        .parallax > use:nth-child(2) {
            animation-delay: -12s;
            animation-duration: 40s;
        }
        .parallax > use:nth-child(3) {
            animation-delay: -16s;
            animation-duration: 52s;
        }
        .parallax > use:nth-child(4) {
            animation-delay: -20s;
            animation-duration: 80s;
        }
        @keyframes move-forever {
            0% {
                transform: translate3d(-90px,0,0);
            }
            100% { 
                transform: translate3d(85px,0,0);
            }
        }
        /*Shrinking for mobile*/
        @media (max-width: 768px) {
            .waves {
                height:40px;
                min-height:40px;
            }
        }
    </style>
    </head>
    <body>
        <div id="loginForm" class="ui middle aligned center aligned grid"  data-aos="fade-up">
            <div class="column">
                <form class="ui large form">
                    <div class="ui basic segment">
                        <img class="ui fluid image" src="img/public/logo.svg" style="pointer-events:none;">
                        <p>Reset Password</p>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                <input id="username" type="text" name="username" placeholder="Username">
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="ticket alternate icon"></i>
                                <input id="token" type="text" name="token" placeholder="Token">
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                <input id="magic" type="password" name="New password" placeholder="New Password">
                            </div>
                        </div>
                        <div id="resetBtn" class="ui fluid basic button"><i class="ui green lock open icon"></i> Reset Password</div>
                        <div id="errmsg" class="ui red message" style="display: none;">
                            <i class="red remove icon"></i> Unknown Error Occured
                        </div>
                        <div id="succmsg" class="ui message" style="display:none;">
                            <i class="ui green check circle icon"></i> Password Updated. <br><small>Redirecting to <a href="/">login page</a> in 3 seconds</small>
                        </div>
                        <div id="countdown" class="ui message" style="color: grey;">
                            <span id="countdownText"><i class="ui loading circle notch icon"></i> Resend email in <span id="countdown-num">30</span> seconds</span>
                            <a href="#" id="resendEmailLink" onclick="sendResetAccountEmail();">Resend Email</a>
                        </div>
                    </div>
                </form>
                <a class="backBtn" href="/">
                    <i class="big chevron circle left icon" style="color: #121d37;"></i>
                </a>
            </div>
            
        </div>
        
        <div id="wavesWrapper">
            <!-- CSS waves-->
            <svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
            viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
                <defs>
                <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
                </defs>
                <g class="parallax">
                <use xlink:href="#gentle-wave" x="48" y="0" fill="rgba(255,255,255,0.7" />
                <use xlink:href="#gentle-wave" x="48" y="3" fill="rgba(255,255,255,0.5)" />
                <use xlink:href="#gentle-wave" x="48" y="5" fill="rgba(255,255,255,0.3)" />
                <use xlink:href="#gentle-wave" x="48" y="7" fill="#fff" />
                </g>
            </svg>
        </div>
        <div class="wavebase">
            <p>Proudly powered by <a href="https://zoraxy.aroz.org" target="_blank">Zoraxy</a></p>
        </div>
    <script>
        AOS.init();

        
        var redirectionAddress = "/";
        var loginAddress = "/api/auth/login";
        $(".checkbox").checkbox();
        $(document).ready(function(){
            var currentdate = new Date(); 
            var datetime = currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/" 
                + currentdate.getFullYear() + " "  
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();
            $("#requestTime").text(datetime);

            //Check if the user already logged in
            $.get("/api/auth/checkLogin",function(data){
                try{
                    if (data === true || data.trim() == "true"){
                    //User already logged in. Redirect to target page.
                    if (redirectionAddress == ""){
                        //Redirect back to index
                        window.location.href = "/";
                    }else{
                        console.log(data);
                        //window.location.href = redirectionAddress;
                    }
                }
                }catch(ex){
                    //Assume not logged in
                    console.log(data);
                }
                
            });
            
        });

        //Bind reset password events
        $('#resetBtn').on('click', function() {
            // Get input values
            var username = $('#username').val();
            var token = $('#token').val();
            var newPassword = $('#magic').val();

            if (token.trim() == ""){
                $("#errmsg").html(`<i class="red circle times icon"></i> Token cannot be empty!`);
                $("#errmsg").show();
                return;
            }

            // Send POST request with input values as data
            let csrfToken = document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content");
            $.ajax({
                url: "/api/account/new",
                method: "POST",
                data: {
                    username: username, 
                    token: token, 
                    newpw: newPassword
                },
                headers: {
                    "X-CSRF-Token": csrfToken,
                },
                success: function(data){
                    // Handle successful response
                    if (data.error != undefined){
                        $("#errmsg").html(`<i class="red circle times icon"></i> ` + data.error);
                        $("#errmsg").show();
                    }else{
                        $("#errmsg").hide();
                        $("#countdown").hide();
                        $("#succmsg").show();
                        setTimeout(function(){
                            window.location.href = "/";
                        }, 3000);
                    }
                },
                error: function(){
                    console.error(error);
                }
            })
        });


        function updateYear() {
            const year = new Date().getFullYear();
            const elements = document.getElementsByClassName("year");
            for (let i = 0; i < elements.length; i++) {
                elements[i].textContent = year;
            }
        }
        updateYear();

        
        function startCountdown() {
            var count = 30;
            var countdownNum = $('#countdown-num');
            countdownNum.text(count);
            $("#countdownText").show();
            $('#resendEmailLink').hide();
            var countdownTimer = setInterval(function() {
                count--;
                if (count === 0) {
                    clearInterval(countdownTimer);
                    $("#countdownText").hide();
                    $('#resendEmailLink').show();
                } else {
                    countdownNum.text(count);
                }
            }, 1000);
        }

        //Send account reset email to preset admin account  
        function sendResetAccountEmail(){
            $("#resendEmailLink").html(`<i class="ui loading spinner icon"></i> Sending Email`);
            $("#resendEmailLink").css({
                "opacity": "0.8",
                "pointer-events": "none"
            });
            $.get("/api/account/reset", function(data){
                $("#resendEmailLink").html(`<a href="#" onclick="sendResetAccountEmail();">Resend Email</a>`);
                $("#resendEmailLink").css({
                    "opacity": "1",
                    "pointer-events": "auto"
                });
                if (data.error !== undefined){
                    alert(data.error);
                }else{
                    //Start countdown again
                    startCountdown();
                }
            });
        }

        $(".thisyear").text(new Date().getFullYear());

        function updateRenderElements(){
            if (window.innerHeight < 520){
                $(".bottombar").hide();
            }else{
                $(".bottombar").show();
            }
        }
        updateRenderElements();
        $(window).on("resize", function(){
            updateRenderElements();
        });

        //Start the countdown on redirect
        startCountdown();
    </script>
    </body>
</html>